package com.jwinf.cdLibary.dao;

import com.alibaba.druid.pool.DruidDataSource;
import com.jwinf.cdLibary.domain.User;
import com.jwinf.cdLibary.tool.JDBCUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author jwinf
 * user操作类 负责数据库交互
 */
public class UserDao {

    // 获取一个druid数据源
    private DruidDataSource dataSource = JDBCUtil.newInstance();
    // 定义一个操作对象
    private QueryRunner queryRunner = new QueryRunner(dataSource);
    // 登录操作
    public List login(User user){
        // sql语句
        String sql = "SELECT * FROM user WHERE username = ? AND password = ? AND state = ?";
        // 参数数组
        Object[] param = {user.getUsername(), user.getPassword(), user.getState()};
        try {
            // 执行sql语句并返回结果
           return queryRunner.query(sql, new BeanListHandler<>(User.class), param);
        } catch (SQLException e) {
            System.out.println(e);
            return null;
        }
    }

    // 查询操作
    public List searchAllUser(){
        // sql语句
        String sql = "SELECT * FROM user";
        try {
            // 执行sql语句并返回结果 装进一个bean的list李
            return queryRunner.query(sql, new BeanListHandler<>(User.class));
        }catch (SQLException e){
            return null;
        }
    }

    // 注册操作
    public boolean register(User user){
       try{
           // sql语句
           String sql = "INSERT INTO user(username, password, tel, addr, state) VALUES(?, ?, ?, ?, ?)";
           // 参数数组
           Object[] param = {user.getUsername(), user.getPassword(), user.getTel(), user.getAddr(), 0};
           // 判断影响的行数 据此来判断是否执行成功
           int result = queryRunner.update(sql, param);
           return result == 1;

       } catch (SQLException e) {
           System.out.println(e);
           return false;
       }
    }

    // 编辑用户
    public boolean edit(User user){
        try {
            // sql语句
            String sql = "UPDATE user SET username = ?, password = ?, tel = ?, addr = ? WHERE id = ?";
            // 参数数组
            Object[] param = {user.getUsername(), user.getPassword(), user.getTel(), user.getAddr(), user.getId()};
            // 通过影响的行数来判断是否执行成功
            int result = queryRunner.update(sql, param);
            return result == 1;
        } catch (SQLException e) {
            System.out.println(e);
            return false;
        }
    }

    // 删除用户
    public boolean delete(User user){
        try {
            // sql语句
            String sql = "DELETE FROM user WHERE id = ?";
            // 参数数组
            Object[] param = {user.getId()};
            // 通过影响的行数来判断是否执行成功
            int result = queryRunner.update(sql, param);
            return result == 1;
        } catch (SQLException e) {
            return false;
        }
    }
}
